/**
 * 问题库
 */
import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Modal, Table, Input, Form, Divider, Switch, Select, Radio, Tree, message } from "antd";
import styles from './knowledgeGather.less';
const InputGroup = Input.Group;
const { TreeNode } = Tree;
const { Option } = Select;
import { cancelKnowledgeCollect, getGenerateAnswersList, postGenerateAnswersDelAnswer, knowledgeAllQaCategoryTree, postGenerateAnswersAddKnowledge } from '@/services/knowledgeGather';

class QuestionAnswerList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			list: [],
			total: 0,
			queryData: {
				queryString: "",
				queryType: "QUESTION",
				queryRangeType: "0",
				current: 1,
				size: 10,
			},
			selectedRowKeys: [],

			questionAnswerVisible: false,
			btnQuestionAnswerLoading: false,
			qaQueryData: {
				knowledgeRange: '1',
				knowledgeType: '0',
			},
			treeList: [],
			categoryQaValue: [],
			cancelLoading: false,
		};
	}

	componentDidMount() {
		this.getQuestionAnswerList();
	}

	getQuestionAnswerList = async () => {
		let { queryData } = this.state;
		let res = await getGenerateAnswersList(queryData);
		console.log(res);
		this.setState({ list: res.records, total: res.total });
	}

	onQueryChange = (value, type) => {
		let { queryData } = this.state;
		queryData[type] = value;
		this.setState({ queryData });
	}

	onQueryClick = () => {
		let { queryData } = this.state;
		queryData.current = 1;
		this.setState({ queryData }, () => this.getQuestionAnswerList())
	}

	onSelectChange = selectedRowKeys => {
		console.log('selectedRowKeys changed: ', selectedRowKeys);
		this.setState({ selectedRowKeys });
	};

	changePage = (page, size) => {
		let { queryData } = this.state;
		queryData.current = page;
		queryData.size = size;
		this.setState({ queryData }, () => this.getQuestionAnswerList())
	}

	removeQa = id => {
		const that = this;
		Modal.confirm({
			title: '是否确定删除该问题',
			okText: '确定',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				let res = await postGenerateAnswersDelAnswer({ ids: [id] });
				console.log(res);
				if (res.code === 0) {
					message.success("操作成功");
					that.onQueryClick();
				}
			},
			onCancel() {
				console.log('取消删除！！！');
			},
		});
	};

	removeQaList = () => {
		const that = this;
		const { selectedRowKeys } = this.state;

		Modal.confirm({
			title: '是否确定删除这些问题',
			okText: '确定',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				let res = await postGenerateAnswersDelAnswer({ ids: selectedRowKeys });
				console.log(res);
				if (res.code === 0) {
					message.success("操作成功");
					that.setState({ selectedRowKeys: [] }, () => that.onQueryClick());
				}
			},
			onCancel() {
				console.log('取消删除！！！');
			},
		});
	}

	proviewQa = id => {
		const { dispatch } = this.props;
		let pathname = "/knowledgeDesign/knowledgeCollect/previewQADetail";
		dispatch(routerRedux.push({ pathname, query: { id: id ? id : undefined } }));
	}

	renderTreeNodes = (data) =>
		data.map((item) => {
			if (item.children) {
				return (
					<TreeNode
						title={item.name}
						key={item.id}
						value={item.id}
						id={item.id}
						disabled={this.state.treeList.map(i => i.id).indexOf(item.id) > -1}
					>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			}
			return <TreeNode
				title={item.name}
				key={item.id}
				value={item.id}
				id={item.id}
				disabled={this.state.treeList.map(i => i.id).indexOf(item.id) > -1}
			/>;
		});

	render() {
		const { getFieldDecorator } = this.props.form;
		const {
			list, queryData, total, selectedRowKeys, cancelLoading,
			questionAnswerVisible, btnQuestionAnswerLoading, qaQueryData, treeList, checkedKeys
		} = this.state;
		const rowSelection = {
			selectedRowKeys,
			onChange: this.onSelectChange,
		};
		const columns = [
			{
				title: '标准问',
				dataIndex: 'question',
				key: 'question',
				width: 420,
				render: (_, row) => {
					let html = '';
					if (row.status == 1) {
						html = (
							<span className={styles.answer_list}>
								<span className={styles.answer_list_question}>{row.question}</span>
								<span className={styles.answer_list_type1}>未阅</span>
							</span>
						)
					} else if (row.status == 2) {
						html = (
							<span className={styles.answer_list}>
								<span className={styles.answer_list_question}>{row.question}</span>
								<span className={styles.answer_list_type2}>已阅</span>
							</span>
						)
					} else {
						html = (
							<span className={styles.answer_list}>
								<span className={styles.answer_list_question}>{row.question}</span>
							</span>
						)
					};
					return html;
				}
			},
			{
				title: '答案',
				dataIndex: 'content',
				key: 'content',
			},
			{
				title: '操作',
				width: 300,
				align: 'center',
				render: (text, row, index) => {
					return (
						<div style={{ display: 'flex', gap: '20px', justifyContent: 'center' }}>
							<Button type="danger" onClick={() => this.removeQa(row.id)} style={{ width: '120px' }}>删除</Button>
							<Button type="primary" onClick={() => this.proviewQa(row.id)} style={{ width: '120px', marginRight: 10 }}>预览</Button>
						</div>
					);
				},
			},
		];
		const formItemLayout = {
			labelCol: { span: 4 },
			wrapperCol: { span: 19 },
		};

		return (
			<div className={styles['question-library']}>
				<Card bordered={false} bodyStyle={{ paddingBottom: 10 }}>
					<div className={styles.top}>
						<Button onClick={this.backRouter} loading={cancelLoading}>取消采编</Button>
						<Button type="primary" onClick={this.addQuestionAnswer}>添加知识点</Button>
					</div>
					<Divider style={{ margin: '16px 0' }} />
					<div className={styles.top}>
						<div>
							<Form layout="inline">
								<Form.Item>
									<InputGroup compact>
										<Select style={{ width: 100 }} value={queryData.queryType} onChange={e => this.onQueryChange(e, 'queryType')}>
											<Option value="ANSWER">答案</Option>
											<Option value="QUESTION">问题</Option>
										</Select>
										<Input style={{ width: 200 }} value={queryData.queryString} placeholder="搜索问题" onChange={e => this.onQueryChange(e.target.value, 'queryString')} />
									</InputGroup>
								</Form.Item>
								<Form.Item>
									<Select style={{ width: 200 }} value={queryData.queryRangeType} onChange={e => this.onQueryChange(e, 'queryRangeType')}>
										<Option value="0">全部</Option>
										<Option value="2">已阅</Option>
										<Option value="1">未阅</Option>
									</Select>
								</Form.Item>
								<Form.Item>
									<Button type="primary" onClick={this.onQueryClick}>搜索</Button>
								</Form.Item>
							</Form>
						</div>
						<div style={{ display: 'flex', gap: "20px" }}>
							<Button type="danger" onClick={this.removeQaList}>批量删除</Button>
							{/* <Button type="primary" onClick={() => this.proviewQa(null)}>预览模式</Button> */}
						</div>
					</div>
					<Table
						rowKey="id"
						bordered
						columns={columns}
						dataSource={list}
						rowSelection={rowSelection}
						scroll={{ x: 1400, y: 560 }}
						pagination={{
							current: queryData.current,
							total: parseInt(total),
							onChange: this.changePage,
							showQuickJumper: true,
							showSizeChanger: true,
							onShowSizeChange: this.changePage,
						}}
					/>
				</Card>

				<Modal
					title={
						<span style={{ fontWeight: 'bold', fontSize: '18px' }}>添加知识点</span>
					}
					visible={questionAnswerVisible}
					width={640}
					centered
					closable={false}
					onOk={this.saveQuestionAnswer}
					onCancel={this.cancelQuestionAnswer}
					footer={[
						<Button type="danger" onClick={this.cancelQuestionAnswer}>取消</Button>,
						<Button type="primary" loading={btnQuestionAnswerLoading} onClick={this.saveQuestionAnswer}>添加</Button>,
					]}
				>
					<div style={{ marginBottom: 12 }}>
						<label style={{ marginRight: 6 }}>知识点范围</label>
						<Radio.Group onChange={e => this.onQaChange(e, 'knowledgeRange')} value={qaQueryData['knowledgeRange']}>
							<Radio value={'1'}>当前选中</Radio>
							<Radio value={'2'}>当前查询数据</Radio>
							<Radio value={'3'}>全部数据</Radio>
						</Radio.Group>
					</div>
					<div>
						<label style={{ marginRight: 6 }}>知识点类型</label>
						<Radio.Group onChange={e => this.onQaChange(e, 'knowledgeType')} value={qaQueryData['knowledgeType']}>
							<Radio value={'0'}>全部</Radio>
							<Radio value={'2'}>已阅</Radio>
							<Radio value={'1'}>未阅</Radio>
						</Radio.Group>
					</div>
					<Divider />
					<div>
						<label>选择知识库目标分类</label>
						<Tree
							selectable={true}
							onSelect={this.onQaChangeCategory}
							selectedKeys={this.state.categoryQaValue}
						>
							{this.renderTreeNodes(treeList)}
						</Tree>
					</div>
				</Modal>
			</div>
		);
	}

	backRouter = () => {
		Modal.confirm({
			title: '确定取消当前文档的采编',
			okText: '确定',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				this.setState({ cancelLoading: true })
				let res = await cancelKnowledgeCollect();
				console.log(res);
				if (res.code === 0) {
					this.setState({ cancelLoading: false })
					const { dispatch } = this.props;
					let pathname = "/knowledgeDesign/knowledgeCollect";
					dispatch(routerRedux.push({ pathname }));
				} else {
					this.setState({ cancelLoading: false })
				}
			},
			onCancel() {
				console.log('取消操作！！！');
			},
		});
	}


	onQaChangeCategory = (value) => {
		this.setState({ categoryQaValue: value });
	}

	addQuestionAnswer = () => {
		this.setState({ questionAnswerVisible: true }, async () => {
			let res = await knowledgeAllQaCategoryTree();
			this.setState({ treeList: res })
		})
	}

	cancelQuestionAnswer = () => {
		this.setState({
			questionAnswerVisible: false,
			treeList: [],
			categoryQaValue: [],
			selectedRowKeys: [],
			qaQueryData: {
				knowledgeRange: '1',
				knowledgeType: '0',
			},
		})
	}

	saveQuestionAnswer = e => {
		e.stopPropagation();
        e.preventDefault();
		let { qaQueryData, categoryQaValue, selectedRowKeys } = this.state;
		if (qaQueryData["knowledgeRange"] == '1' && selectedRowKeys <= 0) {
			return message.error('当前选中的数据为空，请先选择数据，在添加知识点')
		};
		let obj = {
			...qaQueryData,
			ids: qaQueryData["knowledgeRange"] == '1' ? selectedRowKeys : undefined,
			categoryId: categoryQaValue[0],
		};
		this.setState({ btnQuestionAnswerLoading: true }, async () => {
			let res = await postGenerateAnswersAddKnowledge(obj);
			if (res.code === 0) {
				this.setState({ btnQuestionAnswerLoading: false });
				this.cancelQuestionAnswer();
				message.success('操作成功');
				this.getQuestionAnswerList();
			} else {
				let timer = setTimeout(() => {
					this.setState({ btnQuestionAnswerLoading: false });
					clearTimeout(timer);
				}, 5000)
			}
		})
	}

	onQaChange = ({ target: { value } }, type) => {
		console.log(value, type);
		let { qaQueryData } = this.state;
		qaQueryData[type] = value;
		this.setState({ qaQueryData });
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(QuestionAnswerList));
